package edu.ajou.scw;

import java.io.IOException;

import com.google.android.gcm.server.Constants;
import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.Result;
import com.google.android.gcm.server.Sender;

public class GCMThread implements Runnable {
	
	String mRegId;
	String mType;
	String mMessage;
	
	public GCMThread(String regId, String type, String message)
	{
		mRegId = regId;
		mType = type;
		mMessage = message;
	}

	@Override
	public void run() {
		Sender sender;
	    Message msg;
	    
	    sender = new Sender(PushSender.API_KEY);
		Message.Builder builder = new Message.Builder();

		builder.addData("type", mType);
		builder.addData("content", mMessage);
		
		msg = builder.build();		
		
		try {
			if (mRegId.equals(""))
				return;
			Result result = sender.send(msg, mRegId, 5);
			Log.d("GCM Push Message Sent to " + mRegId);
			String error = result.getErrorCodeName();
			String msgId = result.getMessageId();
			
			if (msgId != null)
			{
				String canonicalId = result.getCanonicalRegistrationId();
				if (canonicalId != null)
				{
					System.out.println("# same device has more than on registration ID: update database");
				}
			}
			
			if (error != null)
			{
				if (error.equals(Constants.ERROR_NOT_REGISTERED))
				{
					System.out.println("# application has been removed from device - unregister database");
				}
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
